<?php

class nahoWikiRevisionsWidget extends sfWidgetForm
{

  protected function configure($options = array(), $attributes = array())
  {
    $this->addRequiredOption('page');
  }

  public function render($name, $value = null, $attributes = array(), $errors = array())
  {
    $page = $this->getOption('page');
    if (!is_object($page) || !($page instanceof nahoWikiPage))
    {
      throw new Exception('Option "page" must be instance of nahoWikiPage');
    }

    sfApplicationConfiguration::getActive()->loadHelpers(array('Date', 'I18n', 'nahoWiki'));

    $head = $this->renderContentTag('thead',
      $this->renderContentTag('tr',
        $this->renderContentTag('th', __('Compare'), array('colspan' => 2)).
        $this->renderContentTag('th', __('Revision')).
        $this->renderContentTag('th', __('Date')).
        $this->renderContentTag('th', __('Author')).
        $this->renderContentTag('th', __('Comment'))
      )
    );

    $content = '';
    foreach ($page->getRevisions() as $revision)
    {
      $attrOld = array('name' => $name.'[old]', 'value' => $revision->getRevision(), 'type' => 'radio');
      $attrNew = array('name' => $name.'[new]', 'value' => $revision->getRevision(), 'type' => 'radio');
      if (isset($value['old']) && $value['old'] == $revision->getRevision())
      {
        $attrOld['checked'] = 'checked';
      }
      if (isset($value['new']) && $value['new'] == $revision->getRevision())
      {
        $attrNew['checked'] = 'checked';
      }
      $content .= $this->renderContentTag('tr',
        $this->renderContentTag('td', $this->renderTag('input', $attrOld)).
        $this->renderContentTag('td', $this->renderTag('input', $attrNew)).
        $this->renderContentTag('td', link_to_wiki(null, $page->getName(), array('revision' => $revision->getRevision()))).
        $this->renderContentTag('td', format_datetime($revision->getCreatedAt('U'))).
        $this->renderContentTag('td', link_to_wiki_user(null, $revision->getUserName())).
        $this->renderContentTag('td', $this->renderContentTag('em', sfOutputEscaper::escape(ESC_SPECIALCHARS, $revision->getComment())))
      );
    }
    $body = $this->renderContentTag('tbody', $content);

    return $this->renderContentTag('table', $head.$body, array('class' => 'wiki-history'));
  }

}